1 二叉搜索树介绍
二叉搜索树(BST, Binary Search Tree),也称二叉排序树或二叉查找树。
二叉搜索树:一棵二叉树,可以为空;如果不为空,满足以下性质:
1. 非空左子树的所有键值小于其根结点的键值。
2. 非空右子树的所有键值大于其根结点的键值。
3. 左、右子树都是二叉搜索树。
2 二叉搜索树的主要操作
2.1 二叉搜索树的查找操作
查找从根结点开始,如果树为空,返回NULL
若搜索树非空,则根结点关键字和X进行比较, 并进行不同处理:
若X小于根结点键值,只需在左子树中继续搜索;
如果X大于根结点的键值, 在右子树中进行继续搜索;
若两者比较结果是相等,搜索完成,返回指向此结点的指针。
//查找元素:递归方法
BinarySearchTreeNode find(BinarySearchTreeNode root, int data) {
if (root == null)
return null;//查询失败
if (data < root.getData())
return find(root.getLeft(),data);//在左子树中继续查找
else if (data > root.getData())
return find(root.getRight(),data);//在右子树中继续查找
else
return root;//查找成功, 返回找到的结点的地址
}
//查找元素:非递归方法
BinarySearchTreeNode iterFind(BinarySearchTreeNode root, int data) {
while (root != null) {
if (data < root.getData())
root = root.getLeft();//向左子树中移动, 继续查找
else if (data > root.getData())
root = root.getRight();//向右子树中移动, 继续查找
else
return root;//查找成功, 返回找到的结点的地址
}
return null;//查询失败
}
2.2 查找最大和最小元素
最大元素一定是在树的最右分枝的端结点上
最小元素一定是在树的最左分枝的端结点上
//查找最小元素:递归方法 (最小元素一定是在树的最左分枝的端结点上)
BinarySearchTreeNode findMin(BinarySearchTreeNode root) {
if (root == null)
return null;//空的二叉搜索树,返回null
else if (root.getLeft() == null)
return root;//找到最左叶结点并返回
else
return findMin(root.getLeft());//沿左分支继续查找
}
//查找最小元素:非递归方法 (最小元素一定是在树的最左分枝的端结点上)
BinarySearchTreeNode iterFindMin(BinarySearchTreeNode root) {
if (root == null)
return null;//空的二叉搜索树,返回null
while (root.getLeft() != null)
root = root.getLeft();//沿左分支继续查找
return root;//找到最左叶结点并返回
}
//查找最大元素:递归方法 (最大元素一定是在树的最右分枝的端结点上)
BinarySearchTreeNode findMax(BinarySearchTreeNode root) {
if (root == null)
return null;//空的二叉搜索树,返回null
else if (root.getRight() == null)
return root;//找到最右叶结点并返回
else
return findMax(root.getRight());//沿右分支继续查找
}
//查找最大元素:非递归方法 (最大元素一定是在树的最右分枝的端结点上)
BinaryS